<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 对原有上传类进行扩展，增加从config配置文件读取配置，上传文件按月份存储
 * @author wb_wenjie.wuwj <wb_wenjie.wuwj@alibaba-inc.com>
 * @copyright 2013-1-31 yahoo
 */
class MY_Upload extends CI_Upload
{
	/**
	 * 上传文件的日期存储方式，按月，日
	 * @var string
	 */
	public $storage_mode 	= 'Ym';
	public $date_folder 	= '';
	function __construct($params = array())
	{
		parent::__construct($params);
		
		$this->initialize($params);
		
	}
	
	function initialize($config = array())
	{
		$this->CI =& get_instance();
		$default = array(
			
				'max_size',
				'max_width',
				'max_height',
				'max_filename',
				'allowed_types',
				'file_name',
				'upload_path',
				'overwrite',
				'encrypt_name',
				'remove_spaces',
				'storage_mode'
		);
		foreach ($default as $key)
		{
			$this->$key = isset($config [$key]) ? $config [$key] : $this->CI->config->item($key);
			$method = 'set_' . $key;
			if (method_exists($this, $method))
			{
				$this->$method($this->$key);
			}
		}
		
		// if a file_name was provided in the config, use it instead of the user input
		// supplied file name for all uploads until initialized again
		$this->_file_name_override = $this->file_name;
	}
	
	function do_upload($field = 'userfile')
	{
		$path = $this->upload_path;
		
		// 默认使用“年月”格式
		if (!empty($this->storage_mode))
		{
			$this->date_folder = date($this->storage_mode);
			$path = rtrim($path, '/').'/'.$this->date_folder.'/';
		}
		
		if(!file_exists($path))
		{
			mkdir($path,0777);
		}
		
		// 重新设置上传路径
		parent::set_upload_path($path);
		return parent::do_upload($field);
	}
	
	function data()
	{
		$upload = parent::data();
		$upload['date_folder'] = $this->date_folder;
		return $upload;
	}
}
/* End of file MY_Upload.php */
/* Location: ./application/controllers/MY_Upload.php */